<template>
  <div class="app-container">
  <el-row :gutter="20"> 
    <!--分组数据-->
    <el-col :span="4" :xs="24">
    <div class="head-container">
          <el-input
            v-model="searchgroupname"
            placeholder="请输入组别名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>  
        <div class="head-container">
          <el-tree
            :data="groupList"
            :props="defaultGroupList"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
    </el-col>
    <!--数据-->
    <el-col :span="20" :xs="24">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="设备IP" prop="ip">
          <el-input
            v-model="queryParams.ip"
            placeholder="请输入IP地址"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> 
        <el-form-item label="设备类型" prop="deviceType">
            <el-select
                v-model="queryParams.deviceType"
                placeholder="设备类型"
                clearable
                @keyup.enter.native="handleQuery">   
                <el-option  label="服务器" value="服务器" />
                <el-option  label="网络设备" value="网络设备" />
                <el-option  label="天线" value="天线" />
                <el-option  label="接入设备" value="接入设备" />
                <el-option  label="未知设备" value="未知设备" />
              </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> 
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
            <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['snmp:system:export']"
          >导出</el-button>
        
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="systemList" @selection-change="handleSelectionChange"  >
        <el-table-column type="selection" width="55" align="center" /> 
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备ID" align="center" prop="deviceId" /> 
        <el-table-column label="设备类型" align="center" prop="deviceType" />
        <el-table-column label="设备IP地址" align="center" prop="deviceIp" />  
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template #default="props"> 
            <div  v-if="props.row.sensorsubject && props.row.sensorsubject !== '0'">
              <el-row :gutter="10" class="mb8"> 
                <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="handleRowClick(props.row)">加载传感器数据</el-button>
                  
                </el-col>  
                <el-col :span="1.5"> 
                  <el-button size="mini"  type="text" icon="el-icon-monitor"
                            @click="ShowSensorHistory(props.row)"  >更多传感器信息</el-button> 
                </el-col>
              </el-row>
              <el-table
                v-if="props.row.sensorinfo && props.row.sensorinfo.length > 0"
                :data="props.row.sensorinfo"  border >
                <el-table-column label="传感器ID" align="center" prop="sensorId" />
                <el-table-column label="传感器名称" align="center" prop="sensorName" /> 
                <el-table-column label=" 取值 " prop="sensorInfo"></el-table-column> 
                <el-table-column label="传感器状态" align="center" prop="status" />
                <el-table-column label=" "  prop="description">
                </el-table-column>  
              </el-table>
            </div>
            <div v-else style="text-align: center; padding: 10px; color: #999"> 
                该设备未关联传感器 
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设备基本信息" align="center">
          <template slot-scope="scope">
            <div class="ellipsis" :title="scope.row.sysDecsr">
              {{ scope.row.sysDecsr }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope"> 
            <el-button
              size="mini"
              type="text"
              icon="el-icon-monitor"
              @click="handleSeach(scope.row)"
              v-hasPermi="['snmp:system:remove']"
            >查看</el-button>
            <el-button  type="text"   icon="el-icon-plus" size="mini"
              @click="handleAdd(scope.row)"
              v-hasPermi="['snmp:sensubjectdevice:add']"
            >关联传感器</el-button>   
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> 
    </el-col>
  </el-row>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设备协议信息 -->
    <el-dialog :title="title" :visible.sync="deviceopen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button> 
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible"  width="80%" height="200px"
     custom-class="custom-dialog"
      :show-close="true"
    :destroy-on-close="true"> 
      <Detail :detailData="selectedItem" :key="dialogKey"/>
    </el-dialog>
    <el-dialog :visible.sync="dialoghistoryVisible"  width="80%" height="200px"
     custom-class="custom-dialog"
      :show-close="true"
    :destroy-on-close="true"> 
      <SensorinfohistoryDetail :detailData="selectedDeviceItem" :key="dialoghistoryKey"/>
    </el-dialog>
    <el-dialog :visible.sync="subjectdialogVisible"  width="600" height="200px"
     custom-class="custom-dialog"
      :show-close="true"
    :destroy-on-close="true"> 
      <SubjectInfo :deviceID="selectdeviceId" :deviceName="selectdeviceName"  :deviceIp="selectdeviceIp" :key="dialogKey"/>
    </el-dialog> 

  </div>
</template>

<script>
import { listSystem, getSystem, delSystem, addSystem, updateSystem } from "@/api/snmp/system";
import { getSensorinfoByDeviceId } from "@/api/snmp/sensorinfo";
import { allistGroupinfo} from "@/api/snmp/groupinfo";
import { addSensorinfohistory } from "@/api/snmp/sensorinfohistory";
import axios from "axios";
import Detail from '@/views/snmp/system/deviceDetail.vue';
import SensorinfohistoryDetail from '@/views/snmp/sensorinfohistory/index.vue';
import SubjectInfo from '@/views/snmp/sensubjectdevice/index.vue'; 

export default {
  name: "System",
  components: { Detail,SensorinfohistoryDetail,SubjectInfo },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      systemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      deviceopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ip: null,
        sysDecsr: null,
        sysObjectID: null,
        sysUpTime: null,
        sysContact: null,
        sysName: null,
        sysLocation: null,
        sysService: null,
        groupid:null,
        selfDecs: null,
        deviceType: null,
        deviceName: null,
        icon: null,
        time: null,
        community: null,
        version: null
      },
      // 表单参数
      form: {}, 
      // 表单参数
      sensorform: {},
      selectedItem:null,
      selectedDeviceItem:null,
      //传递传感器关联的设备数据
      selectdeviceId:null,
      selectdeviceName:null,
      selectdeviceIp:null,
      dialogVisible: false,
      dialoghistoryVisible:false,
      subjectdialogVisible:false,
      dialogKey: 0, // 添加一个key变量
      dialoghistoryKey: 0, 
      searchgroupname: '', // 搜索框绑定的值
      groupList:[],
      defaultGroupList: {
        children: "children",
        label: "groupname"
      },
      // 表单校验
      rules: {
        ip: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选树
    searchgroupname(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      
      allistGroupinfo().then(response => { 
        this.groupList = response.data; 
        this.groupList = this.buildTree(response.data); 
        if(this.groupList.length>0){
        this.queryParams.groupid=this.groupList[0].id
        }
      }); 
      listSystem(this.queryParams).then(response => {
        this.systemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.deviceopen=false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ip: null,
        sysDecsr: null,
        sysObjectID: null,
        sysUpTime: null,
        sysContact: null,
        sysName: null,
        sysLocation: null,
        sysService: null,
        selfDecs: null,
        typeName: null,
        name: null,
        icon: null,
        time: null,
        community: null,
        version: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 关联传感器按钮操作 */
    handleAdd(row) {  
      this.title = "传感器场景主题关联设置"+row.deviceId; 
      this.selectdeviceId=row.deviceId; 
      this.selectdeviceName=row.deviceName;
      this.selectdeviceIp=row.deviceIp;
      this.dialogKey += 1; // 每次打开对话框时增加key值以强制重新渲染
      this.subjectdialogVisible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
    },
    handleUpdate1(row) {
      this.reset();
      const id = row.id || this.ids
      getSystem(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 查看*/ 
    handleSeach(row) { 
      this.selectedItem=row.deviceIp;
      this.dialogKey += 1; // 每次打开对话框时增加key值以强制重新渲染
      this.dialogVisible = true;
    },
    /** 提交按钮 */
    submitForm() {},
    submitForm1() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSystem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSystem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备信息编号为"' + ids + '"的数据项？').then(function() {
        return delSystem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('snmp/system/export', {
        ...this.queryParams
      }, `system_${new Date().getTime()}.xlsx`)
    },
    handleRowClick(row) { 
      // 模拟从后台查询传感器数据
      getSensorinfoByDeviceId(row.deviceId).then(response => {   
        row.sensorinfo = response.data; 
      });
    },
     /** 获取传感器数据 */
    fetchSensorData(row) {
     
        // 使用 Promise.all 来确保所有异步请求完成后再继续
        const requests = row.sensorinfo.map((item, index) => {
          const url = "http://" + item.sensorIp+"/";

          return axios.get(url, {
              headers: {
                  "User-Agent": "MyApp/1.0", // 添加 User-Agent
                  "Accept": "application/json", // 添加 Accept
              },
              timeout: 30000, // 设置超时时间为 30 秒
            })
            .then(response => { 
              if (response.data[item.sensorGetdata] !== undefined) {
                // 直接修改原始数组中的对象
                row.sensorinfo[index].sensorInfo = response.data[item.sensorGetdata];
              } else {
                console.warn(`无法找到字段 ${item.sensorGetdata} 的值`);
              }
            })
            .catch(error => { 
              console.error(`请求失败 (${item.sensorIp}):`, error);
              // 可以在这里设置一个默认值或者跳过错误
            });
        });
     

    },
    
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.groupname.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) { 
    if(data.groupname!==undefined&&data.groupname.indexOf("全部")==-1){
      this.queryParams.groupid = data.id;
      }else{
      this.queryParams.groupid=null;
      }  
      this.handleQuery();
    },
    buildTree(data){
      const map = {}; // 用于存储 id 到节点的映射
      const tree = []; // 最终的树形结构 
      // 初始化 map
      data.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      }); 
      // 构建树
      data.forEach((item) => { 
        if (item.fatherid) {
          // 如果有父节点，添加到父节点的 children 中
          map[item.fatherid].children.push(map[item.id]);
        } else {
          // 如果没有父节点，作为根节点
          tree.push(map[item.id]);
        }
      });

      return tree;
    },
    ShowSensorHistory(deviceObj){
      if(deviceObj.deviceId!==null&&deviceObj.deviceId.length>0){
        this.selectedDeviceItem = deviceObj.deviceId;
        this.dialoghistoryKey += 1; 
        this.dialoghistoryVisible = true;
      }
    }

  }
};
</script>
<style>
.custom-dialog .el-dialog__header {
  display: none; /* 隐藏标题栏 */
}

.custom-dialog .el-dialog__body {
  padding: 0; /* 移除默认内边距 */
}
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%; /* 确保根据需要调整宽度 */
}
</style>
